package com.xiekong.rpc.client;

import com.xiekong.rpc.bean.RpcRequest;
import com.xiekong.rpc.bean.RpcResponse;
import com.xiekong.rpc.registry.ServiceRegistry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * RPC 代理（用于创建 RPC 服务代理）
 * @author XieKong
 */
public class RpcProxy {
    private static final Logger logger = LoggerFactory.getLogger(RpcProxy.class);
    private ServiceRegistry serviceRegistry;

    public RpcProxy(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    @SuppressWarnings("unchecked")
    public RpcResponse send(RpcRequest request) throws Throwable {
        request.setRequestId(UUID.randomUUID().toString());
        // 获取RPC服务地址
        String serviceName = request.getInterfaceName();
        String serviceAddress = serviceRegistry.discover(serviceName);
        if (StringUtils.isEmpty(serviceAddress)) {
            throw new RuntimeException("服务地址是空的");
        }
        // 从RPC服务地址中解析主机名与端口号
        String[] addressArray = StringUtils.split(serviceAddress, ":");
        String host = addressArray[0];
        int port = Integer.parseInt(addressArray[1]);
        // 创建RP 客户端对象并发送RPC请求
        RpcClient client = new RpcClient(host, port);
        RpcResponse response = client.send(request);

        if (response == null) {
            throw new RuntimeException("响应Response为null");
        }
        // 返回RPC响应结果
        if (response.hasException()) {
            throw response.getException();
        } else {
            return response;
        }
    }
}
